import pymysql
import sys
from AIDetector_pytorch import Detector
from threading import Thread
import cv2
import os
import time
import traceback
import plotline
from sql_process import *
from flask import jsonify
from retinaface import Retinaface
class facedetect():
    def get_frame(self, det, retinaface, cap, choicenum, im, framenum, ret):
        if ret is True:
            try:
                result = retinaface.detect_image(im)  # 目标跟踪视频检测
                ret, jpeg = cv2.imencode('.jpg', result)
            except:
                result = im
                ret, jpeg = cv2.imencode('.jpg', result)
        else:
            print("无法读取视频")
        return jpeg.tobytes()
    def face_image_detect(self, path):
        image = cv2.imread(path)
        try:
            retinaface = Retinaface()
            flag = 0
            # image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
            result = retinaface.detect_image(image)
            name = str(time.time()) + '.jpg'
            path = 'static/' + name
            cv2.imwrite(path, result)
            return name
        except Exception as e:
            print(e.args)
            print(traceback.format_exc())

    def face_video_detect(self, path):
        try:
            retinaface = Retinaface()
            cap = cv2.VideoCapture(path)
            rate = cap.get(5)
            width = cap.get(3)
            height = cap.get(4)
            fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
            name = str(time.time()) + '.avi'
            path = 'static/' + name
            out = cv2.VideoWriter(path, fourcc, int(rate), (int(width), int(height)), True)
            while (cap.isOpened()):
                ret, im = cap.read()
                if ret == True:
                    try:
                        # im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
                        result = retinaface.detect_image(im)
                    except:
                        result = im
                    out.write(result)
                else:
                    break
            cap.release()
            out.release()
            return name
        except Exception as e:
            print(e.args)
            print(traceback.format_exc())